﻿package kliment.display {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import kliment.utils._Sprite;
	
	/**
	 * ...
	 * @author	Kliment
	 * @version	1.1.6
	 */
	public class BitmapProxy extends Bitmap {
		private var _target_mc:MovieClip;
		private var _realTime:Boolean;
		private var _bitmapDataRectangle:Rectangle;
		private var _clipRecatangle:Rectangle;
		private var _aMatrix:Matrix;
		private var _aColorTransform:ColorTransform;
		private var _aBlendMode:String = BlendMode.NORMAL;
		
		public function BitmapProxy(target_mc:MovieClip, clipRecatangle:Rectangle,  pixelSnapping:String = "auto", smoothing:Boolean = false, realTime:Boolean = true) {
			super(null, pixelSnapping, smoothing);
			_target_mc = target_mc;
			_clipRecatangle = clipRecatangle.clone();
			
			_aColorTransform = new ColorTransform();
			
			_config();
			this.realTime = realTime;
		}
		
		
		private function _config():void {
			_bitmapDataRectangle = new Rectangle(0, 0, _clipRecatangle.width, _clipRecatangle.height);
			_aMatrix = new Matrix(1, 0, 0, 1, - _clipRecatangle.x, -_clipRecatangle.y);
			if (bitmapData)
				bitmapData.dispose();
			bitmapData = new BitmapData(_bitmapDataRectangle.width, _bitmapDataRectangle.height, true, 0x000000);
		}
		
		private function _renderHandler(event:Event = null):void {
			bitmapData.fillRect(_bitmapDataRectangle, 0x000000);
			bitmapData.draw(_target_mc, _aMatrix, _aColorTransform, _aBlendMode);
		}
		
		public function get clipRecatangle():Rectangle { return _clipRecatangle.clone(); }
		public function set clipRecatangle(value:Rectangle):void {
			_clipRecatangle = value.clone();
			_config();
			_renderHandler();
		}
		
		public function get realTime():Boolean { return _realTime; }
		public function set realTime(value:Boolean):void {
			removeEventListener(Event.ENTER_FRAME, _renderHandler);
			if (value) 
				addEventListener(Event.ENTER_FRAME, _renderHandler);
			_renderHandler();
			_realTime = value;
		}
		
		public function remove():DisplayObject {
			realTime = false;
			bitmapData.dispose();
			return _Sprite.remove(this);
		}
	}

}